package combinatorics;

/**
 * author :  apurv verma
 * email  :  dapurv5@gmail.com
 */

public class Permutations {
	

	private static int n=0;
	private static int r=0;
	public static int nPr=0;
	private static Object P[][];
	private static int count=0;
	private static int column[];
	private static boolean available[];
	
	public static int factorial(int num){
		int f=1;
		for(int i=1;i<=num;i++){
			f=f*i;
		}
		return f;
	}

	
	
	public static Object[][] permutations(Object List[], int R){
		Permutations.n=List.length;
		Permutations.r=R;
		
		nPr=factorial(n)/factorial(n-r);
		P=new Object[nPr][r];
		column=new int[n];
		available=new boolean[n];
		for(int i=0;i<n;i++){
			available[i]=true;
		}
		helperPermutations(List,0);
		
		return P;
	}
	
	public static void helperPermutations(Object[] List,int k){
		for(int i=0;i<List.length;i++){
			if(available[i]){
				column[k]=i;
				available[i]=false;
				if(k<r-1){
					helperPermutations(List,k+1);
				}
				else{
					for(int j=0;j<r;j++){
						System.out.print(column[j]);
						P[count][j]=List[column[j]];
					}
					System.out.println();
					count++;
				}
				available[i]=true;
			}
		}
	}
	
	public static void main(String args[]){
		permutations(new Integer[]{0,1,2,3,4,5,6,7},3);
	}
}
